// ai openai :8888/users?question=
// node 内置模块

//- 搭建http服务
const http = require('http');
const url = require('url');
const OpenAI = require('openai');
require('dotenv').config();

const client = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
  //proxy 代理
  baseURL: 'https://api.chatanywhere.tech/v1'
})


const server = http.createServer(async function (req, res) {
  //http 基于请求响应的简单协议 req 请求 res 响应
  // if(req)
  //console.log(req.url);

  if (req.url.indexOf('/users') >= 0) {

    res.setHeader('Access-Control-Allow-Origin', '*'); // 允许所有来源访问，也可以指定具体的域名，如'http://example.com'
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'); // 允许的请求方法
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');


    const urlParams = url.parse(req.url, true);
    // console.log(urlParams);
    const { question, users } = urlParams.query;
    console.log(question, users);


    const prompt = `
    ${users}请根据以上JSON数据，回答${question}这个问题，如果回答不了就回答不清楚！
    `
    const response = await client.chat.completions.create({
      model: 'gpt-3.5-turbo',
      messages: [{ role: "user", content: prompt }],
      temperature: 0, // 控制输出的随机性，0表示更确定的输出
    });


    const result = response.choices[0].message.content || '';
    console.log(result);

    let info = {
      message: result
    }
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/json');
    res.end(JSON.stringify(info))
  }
})






server.listen(8888, function () {
  console.log('server is running')
})


